import { defineStore } from 'pinia'

const MIN_LOADING_TIME = 2000; // 最小显示时间，单位ms

export const useLoadingStore = defineStore('loading', {
  state: () => ({
    loadingCount: 0,
    loadingStart: 0, // 记录loading开始时间
    timer: null as null | ReturnType<typeof setTimeout>
  }),
  getters: {
    isLoading: (state) => state.loadingCount > 0
  },
  actions: {
    startLoading() {
      if (this.loadingCount === 0) {
        this.loadingStart = Date.now();
      }
      this.loadingCount++;
    },
    endLoading() {
      if (this.loadingCount > 0) this.loadingCount--;
      if (this.loadingCount === 0) {
        const elapsed = Date.now() - this.loadingStart;
        if (elapsed < MIN_LOADING_TIME) {
          if (this.timer) clearTimeout(this.timer);
          this.timer = setTimeout(() => {
            this.loadingStart = 0;
            this.timer = null;
            this.loadingCount = 0;
          }, MIN_LOADING_TIME - elapsed);
          this.loadingCount = 1; // 保证isLoading为true
        } else {
          this.loadingStart = 0;
        }
      }
    },
    resetLoading() {
      this.loadingCount = 0;
      this.loadingStart = 0;
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    }
  }
})